/**
 * 路由守卫
 */
import router from '@/router'
import useStore from '@/store'
import { getToken } from '@/utils/cookie'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { isEmpty, isNotEmpty } from '@/utils/validate'

NProgress.configure({ showSpinner: false })

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  const { user, permission, dictStore } = useStore()
  console.log(to.path)
  // 判断该路由是否不需要登录，如果不需要就直接放行
  if (to.meta.noLogin) {
    next()
    // 然后再判断token是否存在
  } else if (getToken()) {
    if (isEmpty(dictStore.dict)) {
      await dictStore.initDict()
    }
    // 判断是否获取了用户的信息，角色，权限
    if (isNotEmpty(user.perms)) {
      // 有就放行
      next()
      NProgress.done()
    } else {
      // 没有就先获取用户信息，权限，菜单等
      const menuList = await user.getUserInfo()
      // 动态添加路由
      const accessRoutes = (await permission.generateRoutes(menuList)) || []
      accessRoutes.forEach((item) => {
        if (!router.hasRoute(item.name)) {
          router.addRoute(item)
        }
      })
      next({ ...to, replace: true })
      NProgress.done()
    }
  } else {
    // 否则进入登录页面
    next(`/login?redirect=${to.path}`)
    NProgress.done()
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
